package so.sao.shop.supplier.service.app.impl;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import so.sao.shop.supplier.config.Constant;
import so.sao.shop.supplier.dao.ReceiptPurchaseDao;
import so.sao.shop.supplier.dao.app.AppPurchaseDao;
import so.sao.shop.supplier.dao.app.AppPurchaseItemDao;
import so.sao.shop.supplier.dao.external.CouponDao;
import so.sao.shop.supplier.domain.ReceiptPurchase;
import so.sao.shop.supplier.domain.external.Coupon;
import so.sao.shop.supplier.pojo.output.AppPurchaseItemOutput;
import so.sao.shop.supplier.pojo.vo.AppPurchaseItemVo;
import so.sao.shop.supplier.pojo.vo.AppPurchaseShipMethodVo;
import so.sao.shop.supplier.pojo.vo.AppPurchasesVo;
import so.sao.shop.supplier.service.app.AppPurchaseItemService;
import so.sao.shop.supplier.util.BeanMapper;
import so.sao.shop.supplier.util.NumberUtil;
import so.sao.shop.supplier.pojo.output.app.AppPurchaseDetailOutput;
import so.sao.shop.supplier.pojo.output.app.AppPurchaseShipMethod;
import so.sao.shop.supplier.pojo.output.app.ReceiptPurchaseVo;
import so.sao.shop.supplier.pojo.output.app.SupplierItemVo;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by acer on 2017/9/7.
 */
@Service
public class AppPurchaseItemServiceImpl implements AppPurchaseItemService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private AppPurchaseItemDao appPurchaseItemDao;
    @Resource
    private AppPurchaseDao appPurchaseDao;

    @Resource
    private CouponDao couponDao;

    @Resource
    private ReceiptPurchaseDao receiptPurchaseDao;







    /**
     * 根据订单ID查询订单详情
     *
     * @param orderId 订单ID
     * @return AppPurchaseItemVo 订单信息
     * @throws Exception 异常
     */
    @Override
    public AppPurchaseItemOutput findOrderItemList(String orderId) throws Exception {
        /**
         * 1.如果查询待付款订单详情用合并编号查询
         * 2.如果查询其他状态订单详情则用订单编号查询
         */
        List<AppPurchasesVo> appPurchasesVoList = new ArrayList<>();
        AppPurchasesVo appPurchasesVos = new AppPurchasesVo();
        Integer orderStatus = 0;
        //计算运费
        BigDecimal totalOrderPostageList = new BigDecimal(0);
        //配送方式列表
        List<AppPurchaseShipMethodVo> appPurchaseShipMethodVos = new ArrayList<>();
        //存放订单ID集合
        List<String> orderIds = new ArrayList<>();
        //存放发票信息
        List<ReceiptPurchase> receiptPurchases = new ArrayList<>();
        //配送方式
        AppPurchaseShipMethodVo appPurchaseShipMethodVo = new AppPurchaseShipMethodVo();
        if(orderId.length() == 28){
            //根据合并支付ID查询所有订单
            appPurchasesVoList = appPurchaseDao.findOrderByPayId(orderId);
            for(AppPurchasesVo appPurchasesVo : appPurchasesVoList){
                //计算运费每一单的运费，即每个用供应商的运费综合
                totalOrderPostageList = totalOrderPostageList.add(appPurchasesVo.getOrderPostage());
                orderIds.add(appPurchasesVo.getOrderId());
            }
            appPurchasesVos = appPurchasesVoList.get(0);
            appPurchasesVos.setOrderPostage(totalOrderPostageList);
            orderStatus = Constant.OrderStatusConfig.PAYMENT;
        }else{
            //查询订单信息
            appPurchasesVos = appPurchaseDao.findOrderByOrderId(orderId);
            orderIds.add(appPurchasesVos.getOrderId());
            if( Objects.equals(appPurchasesVos.getOrderStatus(),Constant.OrderStatusConfig.ISSUE_SHIP) ||
                Objects.equals(appPurchasesVos.getOrderStatus(),Constant.OrderStatusConfig.RECEIVED) ||
                Objects.equals(appPurchasesVos.getOrderStatus(),Constant.OrderStatusConfig.REJECT) ||
                Objects.equals(appPurchasesVos.getOrderStatus(),Constant.OrderStatusConfig.REFUNDED)){

                appPurchaseShipMethodVo = setOrderShipMethod(appPurchasesVos, appPurchaseShipMethodVo);
                appPurchaseShipMethodVos.add(appPurchaseShipMethodVo);

            }
        }

        //获取订单ID集合
        List<String> orderIdList = new ArrayList<>();
        for(AppPurchasesVo appPurchasesVo : appPurchasesVoList){
            orderIdList.add(appPurchasesVo.getOrderId());
        }

        List<AppPurchaseItemVo> appPurchaseItemVoList = new ArrayList<>();
        //业务逻辑
        //1.如果订单状态为待付款的时候（订单状态为1），则把payID相同的订单列出；
        //2.如果订单状态为其他时，则只列出orderId对应的订单
        if(Objects.equals(orderStatus,Constant.OrderStatusConfig.PAYMENT)){
            //根据订单ID列表查询订单详情
            appPurchaseItemVoList = appPurchaseItemDao.findOrderItemList(orderIdList);
        }else{
            //查询详情信息
            appPurchaseItemVoList = appPurchaseItemDao.findOrderItemListByOrderId(orderId);
        }
        AppPurchaseItemOutput appPurchaseItemOutput = null;
        //查询优惠券信息
        Coupon coupon = couponDao.findCouponById(appPurchasesVos.getCouponId());
        if(null != appPurchasesVos){
            appPurchaseItemOutput = BeanMapper.map(appPurchasesVos,AppPurchaseItemOutput.class);
            if(Objects.equals(orderStatus,Constant.OrderStatusConfig.PAYMENT)){
                appPurchaseItemOutput.setOrderId(appPurchasesVos.getPayId());
                appPurchaseItemOutput.setStoreId(null);
                appPurchaseItemOutput.setStoreName(null);
                if (null == coupon){
                    appPurchaseItemOutput.setDiscount("0");
                } else {
                    appPurchaseItemOutput.setDiscount(String.valueOf(coupon.getCouponValue()));
                }
            }
            //输出运费
            //1.如果运费为0，则显示“包邮”
            //2.如果有运费，则输出实际金额的千分值
            if(appPurchasesVos.getOrderPostage().compareTo(new BigDecimal(0)) == 0){
                appPurchaseItemOutput.setOrderPostage("包邮");
            } else {
                appPurchaseItemOutput.setOrderPostage(NumberUtil.number2Thousand(appPurchasesVos.getOrderPostage()));
            }
        }
        //查询发票信息列表
        receiptPurchases = appPurchaseDao.findReceiptByOrderIds(orderIds);
        for (AppPurchaseItemVo appPurchaseItemVo : appPurchaseItemVoList){
            for (ReceiptPurchase receiptPurchase : receiptPurchases){
                if (appPurchaseItemVo.getOrderId().equals(receiptPurchase.getOrderId())){
                    appPurchaseItemVo.setReceiptPurchase(receiptPurchase);
                }
            }
        }


        if(null!=appPurchaseItemVoList && appPurchaseItemVoList.size()>0){
            //当查询订单状态为1时，计算该订单下所有商品总价
            BigDecimal goodsAllPrice = new BigDecimal(0);
            for(AppPurchaseItemVo appPurchaseItemVo : appPurchaseItemVoList){
                //计算总价
                BigDecimal goodsNum = new BigDecimal(appPurchaseItemVo.getGoodsNumber());
                String goodsUnit = appPurchaseItemVo.getGoodsUnitPrice().replaceAll(",","");
                goodsAllPrice = goodsAllPrice.add(goodsNum.multiply(new BigDecimal(goodsUnit)));
            }
            appPurchaseItemOutput.setOrderPrice(String.valueOf(goodsAllPrice));
            if(orderStatus == 1){
                appPurchaseItemOutput.setOrderId(appPurchasesVos.getPayId());
            }
            appPurchaseItemOutput.setAppPurchaseShipMethods(appPurchaseShipMethodVos);
            appPurchaseItemOutput.setAppPurchaseItemVos(appPurchaseItemVoList);
        }

        return appPurchaseItemOutput;
    }





    private AppPurchaseShipMethodVo setOrderShipMethod(AppPurchasesVo appPurchasesVo, AppPurchaseShipMethodVo appPurchaseShipMethodVo) {
        //赋值配送方式
        if(null == appPurchasesVo.getOrderShipMethod()){
            appPurchaseShipMethodVo = null;
        } else {
            if(appPurchasesVo.getOrderShipMethod() == 1){
                appPurchaseShipMethodVo.setOrderShipMethod(appPurchasesVo.getOrderShipMethod());
                appPurchaseShipMethodVo.setDistributorName(appPurchasesVo.getDistributorName());
                appPurchaseShipMethodVo.setDistributorMobile(appPurchasesVo.getDistributorMobile());
            } else {
                appPurchaseShipMethodVo.setOrderShipMethod(appPurchasesVo.getOrderShipMethod());
                appPurchaseShipMethodVo.setLogisticsCompany(appPurchasesVo.getLogisticsCompany());
                appPurchaseShipMethodVo.setOrderShipmentNumber(appPurchasesVo.getOrderShipmentNumber());
            }
        }
        return appPurchaseShipMethodVo;
    }







    @Override
    public AppPurchaseDetailOutput findOrderItemDetail(String id) throws Exception {
        AppPurchaseDetailOutput appPurchaseDetailOutput = new AppPurchaseDetailOutput();


        String orderId = null,payId = null;

        if(isPayId(id)){
            payId = id;
        }else {
            orderId = id;
        }

        List<AppPurchasesVo> purchases = appPurchaseDao.findOrderByOrderIdAndPayId(orderId,payId);

        if(purchases.size() == 0){
            throw new Exception("异常单号:"+id);
        }

        //订单详情信息，从任意一条记录中就可以取到
        getOrderDetail(purchases,appPurchaseDetailOutput);
        //获取供应商的商品详情信息
        getOrderItems(appPurchaseDetailOutput);
        //获取发票信息
        getOrderReceipt(appPurchaseDetailOutput);
        //计算其他信息
        computeOther(appPurchaseDetailOutput);

        //根据前端要求当订单状态为1时（未拆单）设置orderid到最对象最外层。
        if(!appPurchaseDetailOutput.getOrderStatus().equals(Constant.OrderStatusConfig.PAYMENT)){
            appPurchaseDetailOutput.setOrderId(appPurchaseDetailOutput.getSupplierItemVos().get(0).getOrderId());
        }else{
            appPurchaseDetailOutput.setOrderId(null);
        }


        return appPurchaseDetailOutput;
    }

    private void computeOther(AppPurchaseDetailOutput appPurchaseDetailOutput) {

        List<SupplierItemVo> supplierItemVos = appPurchaseDetailOutput.getSupplierItemVos();

        //计算供应商商品价格小计
        for (int i = 0; i < supplierItemVos.size(); i++) {
            SupplierItemVo supplierItemVo = supplierItemVos.get(i);
            List<so.sao.shop.supplier.pojo.output.app.AppPurchaseItemVo> appPurchaseItemVos =
                    supplierItemVo.getAppPurchaseItemVos();
            BigDecimal goodsPrice = new BigDecimal(0.00);
            for (so.sao.shop.supplier.pojo.output.app.AppPurchaseItemVo appPurchaseItemVo : appPurchaseItemVos){
                goodsPrice = goodsPrice.add(new BigDecimal(appPurchaseItemVo.getGoodsTatolPrice()));
            }
            supplierItemVo.setGoodsPrice(goodsPrice.toString());
        }


        //计算订单总运费
        //计算订单总价格
        BigDecimal totalPostage = new BigDecimal(0.00);
        BigDecimal orderPrice = new BigDecimal(0.00);
        for (SupplierItemVo supplierItemVo : supplierItemVos){
            totalPostage = totalPostage.add(new BigDecimal(supplierItemVo.getPostage()));
            orderPrice = orderPrice.add(new BigDecimal(supplierItemVo.getGoodsPrice()));
        }

        //价格设置千分位
        appPurchaseDetailOutput.setOrderPostage(
                new BigDecimal("0.00").compareTo(totalPostage)==0?"包邮":NumberUtil.number2Thousand(totalPostage));
        appPurchaseDetailOutput.setOrderPrice(NumberUtil.number2Thousand(orderPrice));
        for (int i = 0; i < supplierItemVos.size(); i++) {

            SupplierItemVo supplierItemVo = supplierItemVos.get(i);

            List<so.sao.shop.supplier.pojo.output.app.AppPurchaseItemVo> appPurchaseItemVos =
                    supplierItemVo.getAppPurchaseItemVos();

            for (so.sao.shop.supplier.pojo.output.app.AppPurchaseItemVo appPurchaseItemVo : appPurchaseItemVos){

                appPurchaseItemVo.setGoodsTatolPrice(
                        NumberUtil.number2Thousand(
                                new BigDecimal(
                                        appPurchaseItemVo.getGoodsTatolPrice())));

                appPurchaseItemVo.setGoodsUnitPrice(
                        NumberUtil.number2Thousand(
                                new BigDecimal(
                                        appPurchaseItemVo.getGoodsUnitPrice())));
            }

            supplierItemVo.setGoodsPrice(
                    NumberUtil.number2Thousand(
                            new BigDecimal(
                                    supplierItemVo.getGoodsPrice())));

            supplierItemVo.setPostage(
                    "0.00".equals(supplierItemVo.getPostage())?"包邮":
                            NumberUtil.number2Thousand(
                                new BigDecimal(
                                    supplierItemVo.getPostage())));

        }

    }

    //支付号允许的订单状态
    private static final Integer[] payIdAllowStatus = new Integer[]{
            Constant.OrderStatusConfig.PAYMENT
    };
    //订单号允许的订单状态
    private static final Integer[] orderIdAllowStatus = new Integer[]{
            Constant.OrderStatusConfig.ISSUE_SHIP,
            Constant.OrderStatusConfig.RECEIVED,
            Constant.OrderStatusConfig.REJECT,
            Constant.OrderStatusConfig.REFUNDED,
            Constant.OrderStatusConfig.CONFIRM_RECEIVED
    };

    private boolean isAllowStatus(List<AppPurchasesVo> purchases, boolean isPayId) {
        Integer status = purchases.get(0).getOrderStatus();
        logger.debug("订单状态是 ： "+status);
        boolean allow = false;
        if(isPayId){
            allow = ArrayUtils.contains(payIdAllowStatus,status)?true:false;
            logger.debug("是否再允许范围内 ："+ArrayUtils.contains(payIdAllowStatus,status));
        }else{
            allow = ArrayUtils.contains(orderIdAllowStatus,status)?true:false;
            logger.debug("是否再允许范围内 ："+ArrayUtils.contains(orderIdAllowStatus,status));
        }
        return allow;
    }

    private void getOrderReceipt(AppPurchaseDetailOutput appPurchaseDetailOutput) {
        List<String> orderIds = getOrderIds(appPurchaseDetailOutput);
        List<ReceiptPurchase> receiptPurchases = appPurchaseDao.findReceiptByOrderIds(orderIds);

        List<SupplierItemVo> supplierItemVos = appPurchaseDetailOutput.getSupplierItemVos();

        for (int i = 0; i < supplierItemVos.size() ; i++) {

            SupplierItemVo supplierItemVo = supplierItemVos.get(i);

            for (ReceiptPurchase receiptPurchase : receiptPurchases){

                if(supplierItemVo.getOrderId().equals(receiptPurchase.getOrderId())){

                    ReceiptPurchaseVo receiptPurchaseVo = new ReceiptPurchaseVo();
                    BeanUtils.copyProperties(receiptPurchase,receiptPurchaseVo);
                    supplierItemVo.setReceiptPurchase(receiptPurchaseVo);

                }
            }
        }
    }

    private void getOrderItems(AppPurchaseDetailOutput appPurchaseDetailOutput) throws Exception {

        List<String> orderIds = getOrderIds(appPurchaseDetailOutput);
        List<AppPurchaseItemVo> appPurchaseItemVos = appPurchaseItemDao.findOrderItemList(orderIds);
        List<SupplierItemVo> supplierItemVos = appPurchaseDetailOutput.getSupplierItemVos();

        for (int i = 0; i < supplierItemVos.size(); i++) {
            SupplierItemVo supplierItemVo = supplierItemVos.get(i);
            for (int j = 0; j < appPurchaseItemVos.size(); j++) {

                if(appPurchaseItemVos.get(j).getOrderId().equals(supplierItemVo.getOrderId())){
                    so.sao.shop.supplier.pojo.output.app.AppPurchaseItemVo appPurchaseItemVo = new
                            so.sao.shop.supplier.pojo.output.app.AppPurchaseItemVo();

                    BeanUtils.copyProperties(appPurchaseItemVos.get(j),appPurchaseItemVo);
                    supplierItemVo.getAppPurchaseItemVos().add(appPurchaseItemVo);
                }
            }
        }

    }

    private List<String> getOrderIds(AppPurchaseDetailOutput appPurchaseDetailOutput) {
        List<String> orderIds = new ArrayList<>();
        for (SupplierItemVo supplierItemVo : appPurchaseDetailOutput.getSupplierItemVos()){
            orderIds.add(supplierItemVo.getOrderId());
        }
        return  orderIds;
    }

    private void getOrderDetail(List<AppPurchasesVo> purchases, AppPurchaseDetailOutput appPurchaseDetailOutput) {

        BeanUtils.copyProperties(purchases.get(0),appPurchaseDetailOutput);

        logger.debug("[appPurchaseDetailOutput to String] == >> " + appPurchaseDetailOutput.toString());

        List<SupplierItemVo> supplierItemVos = appPurchaseDetailOutput.getSupplierItemVos();
        //设置供应商信息
        for (int i = 0; i < purchases.size(); i++) {


            SupplierItemVo supplierItemVo = new SupplierItemVo();
            BeanUtils.copyProperties(purchases.get(i),supplierItemVo);
            supplierItemVo.setPostage(purchases.get(i).getOrderPostage().toString());
            supplierItemVo.setGoodsPrice(purchases.get(i).getOrderPrice().toString());

            AppPurchaseShipMethod appPurchaseShipMethod = new AppPurchaseShipMethod();
            BeanUtils.copyProperties(purchases.get(i),appPurchaseShipMethod);
            supplierItemVo.setAppPurchaseShipMethods(appPurchaseShipMethod);

            supplierItemVos.add(supplierItemVo);
        }
    }

    private boolean isPayId(String id) {
        //现在就是通过长度来判断是不是payid的
        logger.debug("payid is " + id.length()+". it's length "+id.length());
        return id.length() == 28 ? true : false;
    }




}
